package com.chuanqi.admin.controller; 

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chuanqi.admin.domain.Role;
import com.chuanqi.admin.domain.RoleResource;
import com.chuanqi.admin.dto.RoleTreeNode;
import com.chuanqi.admin.qp.RoleQp;
import com.chuanqi.admin.service.RoleResourceService;
import com.chuanqi.admin.service.RoleService;
import com.chuanqi.admin.service.UserRoleService;
import com.chuanqi.common.utils.SplitIdsStr2ListUtils;

@Controller
@RequestMapping("/authc/role")
public class AdminRoleController {

    @Autowired
    private RoleService roleService;
    
    @Autowired
    private UserRoleService userRoleService;
    
    @Autowired
    private RoleResourceService roleResourceService;
    
    @RequiresPermissions("role:view")
    @RequestMapping(value = "/list", method = RequestMethod.GET)	
	public String showFirstPageGet(Model model) {			
		final long rowCount = roleService.getAllRolesTotalCount();			
		List<Role> roles = roleService.getFirstPageRoles();		
		int pageIndex = 1;
		int pageSize = 10;
		
		String sortName = "ROLE";
		String sortOrder = "ASC";
	    
	    long totalPages = rowCount / pageSize;
	    long mod = rowCount % pageSize;
	    if (mod > 0) {
	    	totalPages++;
	    }
		
	    if( rowCount - (pageIndex-1)*pageSize > 0 ){
	    	model.addAttribute("current", pageIndex);    	   	
	    	model.addAttribute("pageSize", pageSize);	
			
	    	model.addAttribute("sortName", sortName);
			model.addAttribute("sortOrder", sortOrder);	
			
			model.addAttribute("totalPages", totalPages);
			model.addAttribute("total", rowCount);				    
		    
			model.addAttribute("from", pageIndex);
		    model.addAttribute("to", pageSize);
		    
		    model.addAttribute("roles", roles);  
	    }     			
		 
		return "authc/role/list";  
	}

    
    @RequiresPermissions("role:view")
	@RequestMapping(value = "/list", method = RequestMethod.POST)	
	public String queryPagePost(
			@RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
			@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,    		  
    		HttpServletRequest request,
    		Model model) {			
		
		String sortName = request.getParameter("sortName"); 		
		String sortOrder = request.getParameter("sortOrder");	
				
		String role = request.getParameter("role");
		
		if( StringUtils.isBlank(sortName) || StringUtils.isBlank(sortOrder) ){
			sortName = "ROLE";
			sortOrder = "ASC";
		}
		
		long offset = pageIndex > 0 ? (pageIndex - 1) * pageSize : 0;
		RoleQp qp = new RoleQp();
		qp.setOffset(offset);		
		qp.setPageSize(pageSize);
		qp.setSortName(sortName);
		qp.setSortOrder(sortOrder);	
		qp.setRole(role);				
		
		final long rowCount = roleService.getCountByQueryBean(qp);				
		List<Role> roles = roleService.getByQueryBean(qp);			
		
	    long totalPages = rowCount / pageSize;
	    long mod = rowCount % pageSize;
	    if (mod > 0) {
	    	totalPages++;
	    }    
	    
	    long from = (pageIndex - 1) * pageSize + 1;
		long to = 0l;
		
		if(pageIndex<totalPages){			
			to = pageIndex * pageSize;
		}else{
			to = rowCount;
		}			
		
	    if( rowCount - (pageIndex-1)*pageSize > 0 ){
	    	model.addAttribute("current", pageIndex);    	   	
	    	model.addAttribute("pageSize", pageSize);	
			
			model.addAttribute("sortName", sortName);
			model.addAttribute("sortOrder", sortOrder);			
			
			model.addAttribute("totalPages", totalPages);
			model.addAttribute("total", rowCount);				    
		    
			model.addAttribute("from", from);
		    model.addAttribute("to", to);
		    
		    model.addAttribute("roles", roles);  
	    }     			
		 
		return "authc/role/list";  
	}
    
	@RequestMapping(value = "/checkRoleUnique", method = RequestMethod.GET)
	@ResponseBody
	public String checkLoginName(@RequestParam("role") String role) {
		if(roleService.getByRolename(role)!=null){
			return "false";
    	}else {
    		return "true";
		}		 
	}
	
	@RequestMapping(value = "/checkRoleUniqueById/{id}", method = RequestMethod.GET)
	@ResponseBody
	public String checkLoginNameById(@PathVariable("id") Long id, @RequestParam("role") String role) {
		if(roleService.getByRolename(role)!=null && ! role.equals(roleService.getOneById(id).getRole())){
			return "false";
    	}else {
    		return "true";
		}		 
	}	
	
    @RequiresPermissions("user:view")
    @RequestMapping(value = "/getRolesByUserId/{userId}", method = RequestMethod.GET, produces="application/json")
    public @ResponseBody List<RoleTreeNode> getRolesByUserIdPost(@PathVariable("userId") Long userId){	
    	List<Role> alls = roleService.findAll();   	
    	List<Role> mys = roleService.getRolesByUserId(userId);
    	
    	List<RoleTreeNode> roleTreeNodeList = new ArrayList<RoleTreeNode>();	
    	
		for(Role role: alls){
			RoleTreeNode node = new RoleTreeNode(role.getId(), role.getRole(), false);	
			for (Role me : mys) { 					
				if(role.getId().intValue() == me.getId().intValue()){
					node = new RoleTreeNode(role.getId(), role.getRole(), true);
					break;
	        	}					
			}
			roleTreeNodeList.add(node);
		}		
		
		for(RoleTreeNode nd: roleTreeNodeList){
			System.out.println("--name-"+nd.getName()+"--checked--"+nd.getChecked());
		}
		
		return roleTreeNodeList;    	
	}        
    
    @RequiresPermissions("role:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String createGet(Model model) {        
        model.addAttribute("role", new Role());
        model.addAttribute("action", "create");   
        return "authc/role/form";
    }
    
    @RequiresPermissions("role:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(@Valid @ModelAttribute("role") Role role, BindingResult bindingResult, RedirectAttributes redirectAttributes, Model model) {
    	if (bindingResult.hasErrors()) {
        	model.addAttribute("action", "create");        	
        	return "authc/role/form";
        }
    	
    	int createdCount = roleService.createRole(role);    
    	System.out.println("--------------"+createdCount+"--------------");
    	
        redirectAttributes.addFlashAttribute("message", "添加角色成功！");
        return "redirect:/authc/role/list";
    }
    
    @RequiresPermissions("role:update")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String showUpdateForm(@PathVariable("id") Long id, Model model) {        
        model.addAttribute("role", roleService.findOne(id));
        model.addAttribute("action", "update");
        
        return "authc/role/form";
    }

    @RequiresPermissions("role:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(@Valid @ModelAttribute("role") Role role, BindingResult result, RedirectAttributes redirectAttributes, Model model) {
    	if (result.hasErrors()) {
			model.addAttribute("action", "update");
			return "authc/role/form";
		}
		if (role != null) {
			int updatedCount = roleService.updateRole(role);
			System.out.println("--------------"+updatedCount+"--------------");
			redirectAttributes.addFlashAttribute("message", "更新成功");
		}
		
        return "redirect:/authc/role/list";
    }   
    
    @RequiresPermissions("role:update")
    @RequestMapping(value = "/updateRoleResourceByRoleId", method = RequestMethod.POST)
    public String updateRoleResourceByRoleIdPost(HttpServletRequest request, RedirectAttributes redirectAttributes) {
    	Long roleId = Long.parseLong( request.getParameter("roleId") );
    	String idsStr = request.getParameter("resourceIds");    	
    	roleResourceService.deleteRbyR(roleId);    	
    	List<Long> ids = SplitIdsStr2ListUtils.splitIdsStr2List(idsStr);
    	for(int i=0;i<ids.size();i++){
    		Long rId = ids.get(i);
    		RoleResource rr = new RoleResource();
    		rr.setRoleId(roleId);
    		rr.setResourceId(rId);
    		roleResourceService.insertRoleResource(rr);
    	}
		
    	redirectAttributes.addFlashAttribute("message", "更新角色资源成功");
        return "redirect:/authc/role/list";
    }
    
    
    @RequiresPermissions("role:delete")
    @RequestMapping(value = "/delete/{roleId}", method = RequestMethod.GET)
    public String showDeleteForm(@PathVariable("roleId") Long roleId, RedirectAttributes redirectAttributes) {
    	int count = userRoleService.getUserRoleByRoleId(roleId).size();
    	if(count > 0){
    		redirectAttributes.addFlashAttribute("message", "有用户正在使用该角色，无法删除！"); 
    	}else{
    		roleService.deleteRole(roleId);
    		redirectAttributes.addFlashAttribute("message", "删除角色成功！");    		
    	}    	
    	       
        return "redirect:/authc/role/list";
    }    
    
    @RequestMapping(value="/getResourcesRoleId/{roleId}", method=RequestMethod.GET)
	public String resourceTreeGet(@PathVariable("roleId") Long roleId,  Model model){
    	model.addAttribute("roleId", roleId);
    	return "authc/role/resourceTree";
	}
}

